//
//  FCCConversationManager.swift
//  chatUIDemo
//
//  Created by admin on 2025/7/10.
//

import UIKit
import Foundation

// MARK: - 会话管理器协议
protocol FCCConversationManagerDelegate: AnyObject {
    func qfcConversationManager(_ qfcManager: FCCConversationManager, didUpdateConversations qfcConversations: [FCCConversation])
    func qfcConversationManager(_ qfcManager: FCCConversationManager, didDeleteConversation qfcConversation: FCCConversation)
}

// MARK: - 会话管理器
class FCCConversationManager {
    
    // MARK: - 属性
    weak var qfcDelegate: FCCConversationManagerDelegate?
    private var qfcConversations: [FCCConversation] = []
    private let qfcCurrentUserId: String
    private let qfcMessageManager: FCCMessageManager
    
    // MARK: - 初始化
    init(qfcCurrentUserId: String = "current_user", qfcMessageManager: FCCMessageManager? = nil) {
        self.qfcCurrentUserId = qfcCurrentUserId
        self.qfcMessageManager = qfcMessageManager ?? FCCMessageManager(qfcCurrentUserId: qfcCurrentUserId)
        
        // 设置消息管理器代理
        self.qfcMessageManager.qfcDelegate = self
    }
    
    // MARK: - 公共方法
    func qfcGetAllConversations() -> [FCCConversation] {
        return qfcConversations.sorted { $0.qfcTimestamp > $1.qfcTimestamp }
    }
    
    func qfcAddConversation(_ qfcConversation: FCCConversation) {
        if let index = qfcConversations.firstIndex(where: { $0.qfcId == qfcConversation.qfcId }) {
            qfcConversations[index] = qfcConversation
        } else {
            qfcConversations.append(qfcConversation)
        }
        qfcDelegate?.qfcConversationManager(self, didUpdateConversations: qfcGetAllConversations())
    }
    
    func qfcDeleteConversation(_ qfcConversationId: String) {
        if let index = qfcConversations.firstIndex(where: { $0.qfcId == qfcConversationId }) {
            let qfcConversation = qfcConversations[index]
            qfcConversations.remove(at: index)
            qfcDelegate?.qfcConversationManager(self, didDeleteConversation: qfcConversation)
            qfcDelegate?.qfcConversationManager(self, didUpdateConversations: qfcGetAllConversations())
        }
    }
    
    func qfcClearUnreadCount(_ qfcConversationId: String) {
        if let index = qfcConversations.firstIndex(where: { $0.qfcId == qfcConversationId }) {
            qfcConversations[index].qfcUnreadCount = 0
            qfcDelegate?.qfcConversationManager(self, didUpdateConversations: qfcGetAllConversations())
        }
    }
    
    func qfcUpdateConversationLastMessage(_ qfcConversationId: String, qfcMessage: FCCMessage) {
        if let index = qfcConversations.firstIndex(where: { $0.qfcId == qfcConversationId }) {
            qfcConversations[index].qfcLastMessage = qfcMessage
            qfcConversations[index].qfcTimestamp = qfcMessage.qfcTimestamp
            
            // 如果消息不是自己发的，增加未读数
            if !qfcMessage.qfcIsOutgoing {
                qfcConversations[index].qfcUnreadCount += 1
            }
            
            qfcDelegate?.qfcConversationManager(self, didUpdateConversations: qfcGetAllConversations())
        }
    }
    
    // MARK: - 加载模拟会话数据
    func qfcLoadMockConversations() {
        let qfcSystemConversation = FCCConversation(
            qfcUserId: "system",
            qfcUserName: "System",
            qfcUserAvatarUrl: "",
            qfcLastMessage: FCCTextMessage(
                qfcContent: "Welcome to the Chat App!",
                qfcSenderId: "system",
                qfcIsOutgoing: false,
                qfcTimestamp: Date(timeIntervalSinceNow: -3600),
                qfcStatus: .qfcSent
            ),
            qfcUnreadCount: 1,
            qfcTimestamp: Date(timeIntervalSinceNow: -3600),
            qfcIsSystemMessage: true
        )
        
        let qfcInteractiveConversation = FCCConversation(
            qfcUserId: "interactive",
            qfcUserName: "Notifications",
            qfcUserAvatarUrl: "",
            qfcLastMessage: FCCTextMessage(
                qfcContent: "John liked your message",
                qfcSenderId: "interactive",
                qfcIsOutgoing: false,
                qfcTimestamp: Date(timeIntervalSinceNow: -7200),
                qfcStatus: .qfcSent
            ),
            qfcUnreadCount: 2,
            qfcTimestamp: Date(timeIntervalSinceNow: -7200),
            qfcIsInteractiveMessage: true
        )
        
        let qfcUserConversation1 = FCCConversation(
            qfcUserId: "user1",
            qfcUserName: "Mike",
            qfcUserAvatarUrl: "",
            qfcLastMessage: FCCTextMessage(
                qfcContent: "See you tomorrow!",
                qfcSenderId: "user1",
                qfcIsOutgoing: false,
                qfcTimestamp: Date(timeIntervalSinceNow: -10800),
                qfcStatus: .qfcSent
            ),
            qfcUnreadCount: 3,
            qfcTimestamp: Date(timeIntervalSinceNow: -10800)
        )
        
        let qfcUserConversation2 = FCCConversation(
            qfcUserId: "user2",
            qfcUserName: "Sarah",
            qfcUserAvatarUrl: "",
            qfcLastMessage: FCCImageMessage(
                qfcImage: UIImage(systemName: "photo"),
                qfcSenderId: qfcCurrentUserId,
                qfcIsOutgoing: true,
                qfcTimestamp: Date(timeIntervalSinceNow: -14400),
                qfcStatus: .qfcSent
            ),
            qfcUnreadCount: 0,
            qfcTimestamp: Date(timeIntervalSinceNow: -14400)
        )
        
        qfcConversations = [qfcSystemConversation, qfcInteractiveConversation, qfcUserConversation1, qfcUserConversation2]
        qfcDelegate?.qfcConversationManager(self, didUpdateConversations: qfcGetAllConversations())
    }
}

// MARK: - FCCMessageManagerDelegate 实现
extension FCCConversationManager: FCCMessageManagerDelegate {
    func qfcMessageManager(_ qfcManager: FCCMessageManager, didReceiveMessage qfcMessage: FCCMessage) {
        // 当收到新消息时，更新对应的会话
        let qfcConversationId = qfcMessage.qfcSenderId
        
        // 检查是否已存在该用户的会话
        if let index = qfcConversations.firstIndex(where: { $0.qfcUserId == qfcConversationId }) {
            // 更新现有会话
            qfcUpdateConversationLastMessage(qfcConversations[index].qfcId, qfcMessage: qfcMessage)
        } else {
            // 创建新会话
            let qfcNewConversation = FCCConversation(
                qfcUserId: qfcConversationId,
                qfcUserName: "User_\(qfcConversationId)", // Temporary username
                qfcUserAvatarUrl: "",
                qfcLastMessage: qfcMessage,
                qfcUnreadCount: qfcMessage.qfcIsOutgoing ? 0 : 1,
                qfcTimestamp: qfcMessage.qfcTimestamp
            )
            qfcAddConversation(qfcNewConversation)
        }
    }
    
    func qfcMessageManager(_ qfcManager: FCCMessageManager, didUpdateMessage qfcMessage: FCCMessage) {
        // 当消息状态更新时，更新对应的会话
        let qfcConversationId = qfcMessage.qfcSenderId
        
        if let index = qfcConversations.firstIndex(where: { $0.qfcUserId == qfcConversationId }) {
            // 如果最后一条消息是这条消息，则更新会话
            if qfcConversations[index].qfcLastMessage?.qfcId == qfcMessage.qfcId {
                qfcConversations[index].qfcLastMessage = qfcMessage
                qfcDelegate?.qfcConversationManager(self, didUpdateConversations: qfcGetAllConversations())
            }
        }
    }
    
    func qfcMessageManager(_ qfcManager: FCCMessageManager, didFailToSendMessage qfcMessage: FCCMessage, error: Error) {
        // 当消息发送失败时，更新对应的会话
        let qfcConversationId = qfcMessage.qfcSenderId
        
        if let index = qfcConversations.firstIndex(where: { $0.qfcUserId == qfcConversationId }) {
            // 如果最后一条消息是这条消息，则更新会话
            if qfcConversations[index].qfcLastMessage?.qfcId == qfcMessage.qfcId {
                qfcConversations[index].qfcLastMessage = qfcMessage
                qfcDelegate?.qfcConversationManager(self, didUpdateConversations: qfcGetAllConversations())
            }
        }
    }
}